﻿#region Using Directives

using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Globalization;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TeamArchitect.PowerTools.Features;

#endregion

namespace FeatureBuilder.ContribLib.Commands
{
    /// <summary>
    /// Feature Extension Command that compiles a Solution.
    /// </summary>
    [DisplayName("Build Solution")]
    [Description("Builds a Solution.")]
    [Category("IDE")]
    public class BuildSolution : FeatureCommand
    {
        public bool ThrowException { get; set; }

        /// <summary>
        /// Gets the ServiceProvider that we will use to get a reference to DTE.
        /// </summary>
        [Import(typeof(SVsServiceProvider))]
        public IServiceProvider ServiceProvider { get; private set; }

        #region Overrides

        public override void Execute()
        {
            try
            {
                DTE dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE;
                dte.DTE.ExecuteCommand("Build.BuildSolution", String.Empty);

                if (dte.Solution.SolutionBuild.LastBuildInfo != 0)
                {
                    ((EnvDTE80.DTE2)dte).ToolWindows.ErrorList.Parent.Activate();

                    if (ThrowException)
                    {
                        throw new ApplicationException(String.Format(CultureInfo.CurrentCulture, "{0} project(s) failed to compile.", dte.Solution.SolutionBuild.LastBuildInfo));
                    }
                }
            }
            catch { }
        }

        #endregion
    }
}
